# -*- coding:utf-8 -*-

import sublime
import sublime_plugin
from datetime import datetime
import os
import sys
import subprocess

if sys.version_info >= (3,):
	installed_dir, _ = __name__.split('.')
else:
	installed_dir = os.path.basename(os.getcwd())


class CreateTemplate():
	file_path = ''
	file_name = ''
	template = ''

	def __init__(self, path, fn, template):
		self.file_path = path
		self.file_name = fn
		self.template = template

	def get_file_type(self):
		file_parts = self.template.split('.')
		return file_parts[0]

	def create_template(self):
		post_date = datetime.today().strftime('%Y-%m-%d')
		file_type = self.get_file_type()
		if file_type == "post":
			full_file_name = '%s-%s.md' % (post_date, self.file_name)
		else:
			full_file_name = "%s.%s" % (self.file_name, file_type)
		full_path = os.path.join(self.file_path, full_file_name)

		package_dir = os.path.join(sublime.packages_path(), installed_dir)
		tmpl_full_path = os.path.join(package_dir, 'tmpl', self.template)

		with open(tmpl_full_path) as tmpl_fid:
			tmpl_content = tmpl_fid.read()
		with open(full_path, 'w') as fid:
			fid.write(tmpl_content)


class NewFileByTemplateCommand(sublime_plugin.WindowCommand):
	def get_path(self, paths):
		""" Get the path of the file or folder selected
		:param paths:
		:return: the path of the file or the folder selected
		"""
		if paths:
			ret_path = paths[0]
		elif self.window.active_view() and self.window.active_view().file_name():
			ret_path = self.window.active_view().file_name()
		elif self.window.folders():
			ret_path = self.window.folders()[0]
		else:
			sublime.error_message('Terminal: No place to open terminal to')
			return False

		if os.path.isfile(ret_path):
			ret_path = os.path.dirname(ret_path)
		return ret_path

	def run(self, paths=[], template='', parameters=None):
		""" As the menu, this method is default to be run
		This function is the rewrite of the `run` function at super class.
		Take care: the parameters `paths` is must if you want to get current full path selected
		:param paths: the path of the file or folder selected
		:param template: the file name of template
		:param parameters: none
		:return: void
		"""
		dir_path = self.get_path(paths)
		active_view = self.window.active_view()
		tmpl_command = TemplateCommand(active_view)
		tmpl_command.dir_path = dir_path
		tmpl_command.template = template
		tmpl_command.run(active_view)


class OneKeyCommitCommand(sublime_plugin.WindowCommand):
	""" Open terminal from the file select
	"""
	def run(self, paths=[], parameters=None):
		new_file_by_template = NewFileByTemplateCommand(self.window)
		path = new_file_by_template.get_path(paths)
		folders = [x for x in self.window.folders() if path.find(x + os.sep) == 0][0:1]
		project_path = new_file_by_template.get_path(folders)

		if not os.path.exists(project_path):
			sublime.error_message('path `%s` not exists...' % project_path)

		# get the terminal path
		sc = SettingCommand()
		terminal = sc.get_git_cmd_path()

		# One key commit
		os.chdir(project_path)
		package_dir = os.path.join(sublime.packages_path(), installed_dir)
		git_path = os.path.join(package_dir, 'post.bat')
		sublime.status_message('git push file...')

		# print the exec result...
		ret_fid = os.popen('"%s" "%s"' % (terminal, git_path))
		ret_message = ret_fid.read()
		print(ret_message)

		# display the exec result at UI thread
		if 'error_message' in ret_message:
			sublime.error_message(ret_message)
		else:
			sublime.status_message('git push file finished...')		


class OpenTerminalCommand(sublime_plugin.WindowCommand):
	""" Open terminal from the file select
	"""
	def run(self, paths=[], parameters=None):
		new_file_by_template = NewFileByTemplateCommand(self.window)
		path = new_file_by_template.get_path(paths)

		# get the terminal path
		sc = SettingCommand()
		terminal = sc.get_git_cmd_path()

		if not os.path.exists(terminal):
			sublime.error_message('Terminal is not exists in specific path...')
		subprocess.Popen(terminal, cwd=path)


class OpenTerminalFromProjectCommand(sublime_plugin.WindowCommand):
	""" Open terminal from the project
	"""
	def run(self, paths=[], parameters=None):
		new_file_by_template = NewFileByTemplateCommand(self.window)
		path = new_file_by_template.get_path(paths)
		folders = [x for x in self.window.folders() if path.find(x + os.sep) == 0][0:1]
		project_path = new_file_by_template.get_path(folders)

		# get the terminal path
		sc = SettingCommand()
		terminal = sc.get_git_cmd_path()

		if not os.path.exists(terminal):
			sublime.error_message('Terminal is not exists in specific path...')
		subprocess.Popen(terminal, cwd=project_path)


class TemplateCommand(sublime_plugin.TextCommand):
	# variable to store path
	dir_path = ''

	# the name of template file
	template = ''

	def run(self, edit):
		""" Rewrite of function `run` in sublime_plugin.TextCommand
		:param edit:
		:return: void
		"""
		self.view.window().show_input_panel("文件名称:", "", lambda s: self.on_done(s), None, None)

	def on_done(self, s):
		""" Callback of `run` function of this class
		:param s: input value
		:return: void
		"""
		create_template = CreateTemplate(self.dir_path, s, self.template)
		create_template.create_template()
		sublime.status_message('文件生成成功...')


class SettingCommand():
	# setting of this plugin
	settings = ''

	# the path of git installed
	git_path = ''

	# the path of 'git-cmd.exe'
	terminal = ''

	def __init__(self):
		self.settings = sublime.load_settings('SideBarTmpl.sublime-settings')
		self.git_path = self.settings.get('git_path')
		self.terminal = self.settings.get('terminal')

	def get_git_path(self):
		return self.git_path

	def get_git_cmd_path(self):
		return os.path.join(self.git_path, self.terminal)


